package com.example.contentclient;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.example.contentclient.Util.FileUtil;
import com.example.contentclient.Util.PermissionUtil;
import com.example.contentclient.Util.SizeChangeUtil;
import com.example.contentclient.pojo.ImageInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ProviderMmsActivity extends AppCompatActivity {
    private static final String[]PERMISSIONS=new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private static final int PERMISSION_REUQEST_CODE=1;
    private EditText phone;
    private EditText title;
    private EditText message;
    private List<ImageInfo> mImageList=new ArrayList<>();
    private GridLayout gl_appendix;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_provider_mms);
        gl_appendix = findViewById(R.id.gl_appendix);
        phone = findViewById(R.id.et_phone);
        title = findViewById(R.id.et_phone);
        message = findViewById(R.id.et_phone);
        //手动让MediaStore扫描入库
        MediaScannerConnection.scanFile(this,
                new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()},
                null,null);
        //先检查权限
        if(PermissionUtil.checkPermission(this,PERMISSIONS,PERMISSION_REUQEST_CODE))
        {
            //加载图像信息
            LoadImageList();
            //显示图像
            showImageGrid();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==PERMISSION_REUQEST_CODE&& PermissionUtil.checkGrant(grantResults))
        {
            //加载图像信息
            LoadImageList();
            //显示图像
            showImageGrid();
        }
    }

    private void showImageGrid() {
        gl_appendix.removeAllViews();
        for (ImageInfo imageInfo : mImageList) {
            ImageView iv_appendix=new ImageView(this);
            Bitmap bitmap = BitmapFactory.decodeFile(imageInfo.path);
            //设置图片来源
            iv_appendix.setImageBitmap(bitmap);
            //设置图像的缩放类型
            iv_appendix.setScaleType(ImageView.ScaleType.CENTER);
            //设置图像的布局参数
            int px= SizeChangeUtil.dp2px(this,110);
            ViewGroup.LayoutParams params=new ViewGroup.LayoutParams(px,px);
            iv_appendix.setLayoutParams(params);
            //设置ImageView的内部间距
            int padding= SizeChangeUtil.dp2px(this,5);
            iv_appendix.setPadding(padding,padding,padding,padding);
            //设置点击事件
            iv_appendix.setOnClickListener(v->{
                sendMms(phone.getText().toString(),title.getText().toString(),message.getText().toString(),imageInfo.path);
            });
            //将视图添加到网格布局
            gl_appendix.addView(iv_appendix);
        }
    }

    //加载图片列表
    @SuppressLint("Range")
    private void LoadImageList() {
        String []columns=new String[]{
                MediaStore.Images.Media._ID,//编号
                MediaStore.Images.Media.TITLE,//标题
                MediaStore.Images.Media.SIZE,//文件大小
                MediaStore.Images.Media.DATA//文件路径
        };
        Cursor cursor = getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                columns,
                MediaStore.Images.Media.SIZE + " < 307200",
                null,
                MediaStore.Images.Media.SIZE + " DESC"
        );
        int count=0;
        if(cursor!=null&& count<3)
        {
            while(cursor.moveToNext())
            {
                ImageInfo image=new ImageInfo();
                image.id=cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID));
                image.name=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.TITLE));
                image.size=cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.SIZE));
                image.path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                if(FileUtil.checkFileUri(this,image.path))
                {
                    count++;
                    mImageList.add(image);
                }
                Log.d("tang", "image:"+image.toString());
            }
        }
    }
    private void sendMms(String phone, String title, String message,String path) {
        Uri uri=null;
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N)
        {
            //通过FileProvider获取文件的URI访问方式
            uri= FileProvider.getUriForFile(this,getString(R.string.file_provider),new File(path));
            Log.d("tang", String.format("new uri:%s",uri.toString()));
        }
        else {
            uri = Uri.parse(path);
        }


        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent的接受者将被允许读取Intent携带的 URI数据
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra("address",phone);
        intent.putExtra("title",title);
        intent.putExtra("sms_body",message);
        //彩信的图片附件
        intent.putExtra(Intent.EXTRA_STREAM,uri);
        //设置彩信的附件为图片类型
        intent.setType("image/*");
        startActivity(intent);
        Toast.makeText(this, "请在弹窗中选择短信或者信息应用", Toast.LENGTH_SHORT).show();
    }
}
